<template>
  <a-modal
    :title="title"
    :visible="visible"
    :footer="null"
    :width="1200"
    @cancel="visible = false"
  >
    <a-tabs
      type="card"
      class="mb20"
      :active-key="activeKey"
      @change="(key) => (activeKey = key)"
    >
      <a-tab-pane
        key="1"
        tab="当前流程"
      >
        <img
          style="width: 100%"
          :src="flowChart"
        >
        <a-table
          :columns="currentColumnApprove"
          :data-source="currentTableData"
          row-key="id"
        >
          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>
        </a-table>
      </a-tab-pane>
      <a-tab-pane
        key="2"
        tab="历史流程"
      >
        <b-table
          ref="historyTable"
          :columns="historyColumns"
          :request="historyTableData2"
        >
          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span>
          <!-- <div slot="operation" slot-scope="text, record, index" class="pub-table-list-action"> -->
          <!--todo                         -->
          <!--                        <span @click="handleEdit(record, 3)">查看</span>-->
          <!-- </div> -->
        </b-table>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>
<script>
import { getCurrentProcess, getFlowChart2, getProcInstByBusiness } from '@/api/process'
import { getOrgEmployeesListBy, getProcessGroupPerson } from '@/api/commons'
import JosnBig from 'json-bigint'

export default {
  name:'a'+Date.now(),
  props: {
    title: {
      type: String,
      default: '历史记录选择'
    },
    row: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      currentColumnApprove: [
        {
          title: '序号',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 70
        },
        {
          title: '节点名称',
          dataIndex: 'taskName'
        },
        {
          title: '处理人',
          dataIndex: 'userName'
        },
        {
          title: '审批意见',
          dataIndex: 'opinions'
        },
        {
          title: '开始时间',
          dataIndex: 'createTime'
        },
        {
          title: '滞留时间',
          dataIndex: 'durationInMillis'
        },
        {
          title: '结束时间',
          dataIndex: 'endTime'
        }
      ],
      currentTableData: [],
      historyColumns: [
        {
          title: '序号',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 70
        },
        {
          title: '节点名称',
          dataIndex: 'name'
        },
        {
          title: '发起人',
          dataIndex: 'userName'
        },
        {
          title: '发起时间',
          dataIndex: 'startTime'
        },
        {
          title: '滞留时间',
          dataIndex: 'durationTime'
        },
        {
          title: '结束时间',
          dataIndex: 'endTime'
        }
      ],
      historyTableData2: async (params) => {
        params = Object.assign({}, params, { businessId: this.id })
        let res = await getProcInstByBusiness(params)
        const userIds = []
        res.data.forEach((item) => {
          userIds.push(item.startUser)
          item.endTime = item.endTime || '进行中'
          item.durationTime = item.durationTime || '进行中'
          item.description = []
        })
        if (userIds.length) {
          let employees = await getOrgEmployeesListBy({ userIds })
          res.data.forEach((r) => {
            employees.data.some((e) => {
              if (e.startUser === r.userId) {
                r.userName = e.name
                return true
              }
            })
          })
          console.log('数据返回对象：', res)
          return res
        }
        return res
        // this.historyTableData = res.data
      },
      loading: false,
      flowChart: '',
      type: 1,
      activeKey: '1',
      visible: false,
      id: ''
    }
  },
  methods: {
    open() {
      this.visible = true
    },
    async getFlowChart(id) {
      let res = await getFlowChart2(id)
      if (res.code === 200) {
        if (typeof res.data === 'string') {
          this.flowChart = 'data:image/png;base64,' + res.data
        } else {
          this.flowChart = ''
        }
      }
    },
    async getCurrentTableData(id) {
      this.loading = true
      let res = await getCurrentProcess(id)
      const processData = res.data
      let userIds = []
      const groupList = []
      res.data.forEach((item) => {
        userIds.push(item.assignee)
        item.userName = item.userName || ''
        item.endTime = item.endTime || item.completed !== 2 && '进行中' || ''
        item.durationInMillis = item.durationInMillis || item.completed !== 2 && '进行中' || ''
        if (item.formData) {
            try {
                const formDataObj = JosnBig.parse(item.formData)
                item.opinions = formDataObj.opinions
                item.auditResult = formDataObj.reject === 'true' ? '审批不通过' : formDataObj.reject === 'false' ? '审批通过' : ''
            } catch(e) {
                console.error(e)
            }
        } else {
            item.opinions = ''
            item.auditResult = ''
        }
        // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
        if(item.groupId && item.completed !== 1) {
            try {
                const groupIdObj = JosnBig.parse(item.groupId)
                groupList.push({...groupIdObj, processTaskId: item.taskDefKey})
            } catch(e) {
                console.error(e)
            }
        }
        item.description = []
      })
      // 获取后面节点的处理人列表
      groupList.length && getProcessGroupPerson({
          assignGroup:groupList
      }).then(res => {
          const targetObj = res.data || {}
          processData.forEach(item => {
              if(targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
                  item.userName = targetObj[item.taskDefKey].map(item => item.name).join('、')
              }
          })              
      })
      if (userIds.length) {
        let employees = await getOrgEmployeesListBy({ userIds })
        res.data.forEach((r) => {
          employees.data.some((e) => {
            if (e.userId === r.assignee) {
              r.userName = e.name
              return true
            }
          })
        })
      }
      // console.log('数据返回对象：', res)
      this.currentTableData = res.data
    }
  },
  watch: {
    async visible(val) {
      if (val) {
        this.id = this.row.businessId
        this.loading = true
        await this.getFlowChart(this.id)
        await this.getCurrentTableData(this.id)
        this.loading = false
      } else {
        this.flowChart = ''
        this.activeKey = '1'
        this.type = 1
      }
    },
    async activeKey(v) {
      if (v === '1') {
        this.loading = true
        await this.getFlowChart(this.id)
        await this.getCurrentTableData(this.id)
        this.loading = false
      } else {
        if (this.$refs.historyTable) {
          this.$refs.historyTable.getData()
        }
      }
    }
  }
}
</script>
